package com.jxl.domain.service.impl;


import com.jxl.common.entity.PageResult;
import com.jxl.common.enums.DeletedCodeEnum;
import com.jxl.common.redis.RedisUtil;
import com.jxl.common.util.ContextUtil;
import com.jxl.domain.convert.SubjectInfoConvert;
import com.jxl.domain.entity.SubjectInfoBO;
import com.jxl.domain.entity.SubjectOptionBO;
import com.jxl.domain.handler.subject.SubjectTypeHandler;
import com.jxl.domain.handler.subject.SubjectTypeHandlerFactory;
import com.jxl.domain.service.SubjectInfoDomainService;
import com.jxl.domain.service.SubjectLikedDomainService;
import com.jxl.infra.basic.entity.SubjectInfo;
import com.jxl.infra.basic.entity.SubjectLabel;
import com.jxl.infra.basic.entity.SubjectMapping;
import com.jxl.infra.basic.es.entity.SubjectInfoEs;
import com.jxl.infra.basic.es.util.EsUtil;
import com.jxl.infra.basic.service.SubjectInfoService;
import com.jxl.infra.basic.service.SubjectLabelService;
import com.jxl.infra.basic.service.SubjectMappingService;
import com.jxl.infra.entity.UserInfo;
import com.jxl.infra.rpc.AuthUserRpc;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;


@Service
public class SubjectInfoDomainServiceImpl implements SubjectInfoDomainService {

    @Resource
    private SubjectInfoService subjectInfoService;

    @Resource
    private SubjectTypeHandlerFactory subjectTypeHandlerFactory;

    @Resource
    private SubjectMappingService subjectMappingService;

    @Resource
    private SubjectLabelService subjectLabelService;

    @Resource
    private EsUtil esUtil;

    //排行榜的key
    private static final String RANK_KEY = "subject_rank";

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private AuthUserRpc authUserRpc;

    @Resource
    private SubjectLikedDomainService subjectLikedDomainService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(SubjectInfoBO subjectInfoBO) {
        //进行类型转换
        SubjectInfo subjectInfo =
                SubjectInfoConvert.INSTANCE.convertBOToSubjectInfo(subjectInfoBO);
        //题目主表的信息插入
        subjectInfo.setIsDeleted(DeletedCodeEnum.UN_DELETE.getCode());
        subjectInfoService.insert(subjectInfo);
        //接下来是题目详细表的信息插入
        SubjectTypeHandler handler = subjectTypeHandlerFactory.getHandler(subjectInfo.getSubjectType());
        subjectInfoBO.setSubjectId(subjectInfo.getId());
        handler.add(subjectInfoBO);
        //同时进行题目分类标签中间表的数据插入
        List<Long> categoryIds = subjectInfoBO.getCategoryIds();
        List<Long> labelIds = subjectInfoBO.getLabelIds();
        List<SubjectMapping> subjectMappings = new LinkedList<>();
        categoryIds.forEach(categoryId->{
            labelIds.forEach(labelId->{
                SubjectMapping subjectMapping = new SubjectMapping();
                subjectMapping.setSubjectId(subjectInfo.getId());
                subjectMapping.setCategoryId(categoryId);
                subjectMapping.setLabelId(labelId);
                subjectMapping.setIsDeleted(DeletedCodeEnum.UN_DELETE.getCode());
                subjectMappings.add(subjectMapping);
            });
        });
        subjectMappingService.insertBatch(subjectMappings);

        //同时进行添加到es中
        SubjectInfoEs subjectInfoEs = SubjectInfoConvert.
                INSTANCE.conertSubejctInfoToSubejctEs(subjectInfo);
        esUtil.add("subject_info",subjectInfoEs);
        //同时添加redis贡献榜
        redisUtil.addScore(RANK_KEY, ContextUtil.getUserLoginId(),1);
    }

    @Override
    public PageResult<SubjectInfoBO> querySubjectPage(SubjectInfoBO subjectInfoBO) {
        PageResult<SubjectInfoBO> pageResult = new PageResult<>();
        pageResult.setPageNo(subjectInfoBO.getPageNo());
        pageResult.setPageSize(subjectInfoBO.getPageSize());
        SubjectInfo subjectInfo =
                SubjectInfoConvert.INSTANCE.convertBOToSubjectInfo(subjectInfoBO);
        //查询总数
        Long count =
                subjectInfoService.getSubjectInfoPageCount(subjectInfo,subjectInfoBO.getCategoryId(),subjectInfoBO.getLabelId());
        //查询数据
        List<SubjectInfo> subjectInfos = subjectInfoService.getSubjectInfoPage(subjectInfo,subjectInfoBO.getCategoryId(),subjectInfoBO.getLabelId(),
                subjectInfoBO.getPageNo(),subjectInfoBO.getPageSize());
        //再进行组装
        List<SubjectInfoBO> subjectInfoBOS =
                SubjectInfoConvert.INSTANCE.convertToSubjectInfoBO(subjectInfos);
        pageResult.setResult(subjectInfoBOS);
        pageResult.setTotal(count);
        return pageResult;
    }

    @Override
    public SubjectInfoBO querySubjectInfo(SubjectInfoBO subjectInfoBO) {
        SubjectInfo subjectInfo = subjectInfoService.queryById(subjectInfoBO.getId());
        Integer subjectType = subjectInfo.getSubjectType();
        SubjectTypeHandler handler = subjectTypeHandlerFactory.getHandler(subjectType);
        SubjectOptionBO query = handler.query(subjectInfo.getId());
        SubjectInfoBO bo = SubjectInfoConvert.INSTANCE.convertOptionAndInfoToBo(query,subjectInfo);
        SubjectMapping subjectMapping = new SubjectMapping();
        subjectMapping.setSubjectId(subjectInfo.getId());
        subjectMapping.setIsDeleted(DeletedCodeEnum.UN_DELETE.getCode());
        List<SubjectMapping> subjectMappings = subjectMappingService.queryLabelByCategoryIds(subjectMapping);
        List<Long> labelIds = new ArrayList<>();
        subjectMappings.forEach(subjectMapping1 -> {
            labelIds.add(subjectMapping1.getLabelId());
        });
        List<SubjectLabel> labelList = subjectLabelService.queryByIds(labelIds);
        List<String> labelNames = new LinkedList<>();
        labelList.forEach(labelList1 ->{
            labelNames.add(labelList1.getLabelName());
        });
        bo.setLabelNames(labelNames);
        //同时设置题目点赞数量
        bo.setLiked(subjectLikedDomainService.isLiked(subjectInfo.getId().toString(),ContextUtil.getUserLoginId()));
        bo.setLikedCount(subjectLikedDomainService.getLikedCount(subjectInfo.getId().toString()));
        return bo;
    }

    @Override
    public PageResult<SubjectInfoEs> querySubejctInfoEs(SubjectInfoBO subjectInfoBO) {
       return esUtil.page("subject_info",subjectInfoBO.getKeyWord(),subjectInfoBO.getPageNo(),subjectInfoBO.getPageSize(),SubjectInfoEs.class);
    }

    @Override
    public List<SubjectInfoBO> getContributeList() {
        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisUtil.rankWithScore(RANK_KEY, 0, 5);
        if (CollectionUtils.isEmpty(typedTuples)) {
            return Collections.emptyList();
        }
        List<SubjectInfoBO> boList = new LinkedList<>();
        typedTuples.forEach((rank -> {
            SubjectInfoBO subjectInfoBO = new SubjectInfoBO();
            subjectInfoBO.setSubjectCount(rank.getScore().intValue());
            UserInfo userInfo = authUserRpc.getUserInfo(rank.getValue());
            subjectInfoBO.setCreateUser(userInfo.getNickName());
            subjectInfoBO.setCreateUserAvatar(userInfo.getAvatar());
            boList.add(subjectInfoBO);
        }));
        return boList;

    }
}
